﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;

namespace Pixysoft.Web
{
    public class SessionHelper
    {
        private static SessionHelper instance;
        public static SessionHelper Instance
        {
            get
            {
                lock (typeof(SessionHelper))
                {
                    if (instance == null)
                        instance = new SessionHelper();
                    return instance;
                }
            }
        }

        /// <summary>
        /// 添加数据到缓存
        /// </summary>
        /// <param name="id"></param>
        /// <param name="value"></param>
        public void AddSession(string id, object value)
        {
            RemoveSession(id);

            HttpContext.Current.Session[id] = value;
        }

        /// <summary>
        /// 取得数据，如果不存在就返回null
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="id"></param>
        /// <returns></returns>
        public T GetSession<T>(string id)
        {
            object _value = HttpContext.Current.Session[id];

            if (_value == null)
                return default(T);

            return (T)_value;
        }

        /// <summary>
        /// 删除缓存
        /// </summary>
        /// <param name="id"></param>
        public void RemoveSession(string id)
        {
            object _value = HttpContext.Current.Session[id];

            if (_value != null)
                HttpContext.Current.Session.Remove(id);
        }

        /// <summary>
        /// 清空session
        /// </summary>
        public void ClearSession()
        {
            HttpContext.Current.Session.Clear();
        }
    }
}
